from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions
import jwt
from app01.models import UserInfo
from rest_framework_jwt.settings import api_settings
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
class JwtAuthentication(BaseAuthentication):
    def authenticate(self, request):
        # 取出前端传入的token串
        token = request.META.get('HTTP_TOKEN')
        # 通过token获得payload
        try:
            payload = jwt_decode_handler(token)  # 通过token串获得payload，验签（是否被篡改），检查过期时间
        except jwt.ExpiredSignature:
            msg = '签名过期'
            raise exceptions.AuthenticationFailed(msg)
        except jwt.DecodeError:
            msg = '解码错误'
            raise exceptions.AuthenticationFailed(msg)
        except jwt.InvalidTokenError:
            raise exceptions.AuthenticationFailed()
        # 通过payload获得当前用户(从自己写的表中取)
        user_obj = UserInfo.objects.filter(pk=payload['user_id']).first()
        # user = {'id':payload['user_id'],'username':payload['username']}
        # user = UserInfo(id=payload['user_id'],username=payload['username'])
        # 返回当前用户
        return user_obj,token
from rest_framework_jwt import settings  # drf-jwt